\input{../slides/common/slides_common}

\newif\ifbook
\input{../shared/chisel}

\title{A Little Bit of Scala and Chisel Background}
\author{Martin Schoeberl}
\date{\today}
\institute{Technical University of Denmark}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

\begin{frame}[fragile]{Chisel and Scala}
\begin{itemize}
\item Chisel is a library written in Scala
\begin{itemize}
\item Import the library with \code{import chisel3.\_}
\end{itemize}
\item Chisel code is Scala code
\item When it is run is \emph{generates} hardware
\begin{itemize}
\item Verilog for synthesize
\item Scala netlist for simulation (testing)
\end{itemize}
\item Chisel is an embedded domain specific language
\item Two languages in one can be a little bit confusing
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala}
\begin{itemize}
\item Is object oriented
\item Is functional
\item Strongly typed with very good type inference
\item Runs on the Java virtual machine
\item Can call Java libraries
\item Consider it as Java++
\begin{itemize}
\item Can almost be written like Java
\item With a more lightweight syntax
\item Compiled to the JVM
\item Good Java interoperability
\item Many libraries available
\end{itemize}
\item \url{https://docs.scala-lang.org/tour/tour-of-scala.html}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala Hello World}
\begin{chisel}
object HelloWorld extends App {
  println("Hello, World!")
}
\end{chisel}
\begin{itemize}
\item Compile with \code{scalac} and run with \code{scala}
\item You can even use Scala as scripting language
\item Show both
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Scala Values and Variables}
\begin{chisel}
// A value is a constant
val i = 0
// No new assignment; this will not compile
i = 3

// A variable can change the value
var v = "Hello"
v = "Hello World"

// Type usually inferred, but can be declared
var s: String = "abc"
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Simple Loops}
\begin{chisel}
// Loops from 0 to 9
// Automatically creates loop value i
for (i <- 0 until 10) {
  println(i)
}
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Conditions}
\begin{chisel}
for (i <- 0 until 10) {
  if (i%2 == 0) {
    println(i + " is even")
  } else {
    println(i + " is odd")
  }
}
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Scala Arrays and Lists}
\begin{chisel}
// An integer array with 10 elements
val numbers = new Array[Integer](10)
for (i <- 0 until numbers.length) {
  numbers(i) = i*10
}
println(numbers(9))


// List of integers
val list = List(1, 2, 3)
println(list)
// Different form of list construction
val listenum = 'a' :: 'b' :: 'c' :: Nil
println(listenum)
\end{chisel}
\end{frame}


\begin{frame}[fragile]{Scala Classes}
\begin{chisel}
// A simple class
class Example {
  // A field, initialized in the constructor
  var n = 0
  
  // A setter method
  def set(v: Integer) = {
    n = v
  }
  
  // Another method
  def print() = {
    println(n)
  }
}
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Scala (Singleton) Object}
\begin{chisel}
object Example {}
\end{chisel}
\begin{itemize}
\item For \emph{static} fields and methods
\begin{itemize}
\item Scala has no static fields or methods like Java
\end{itemize}
\item Needed for \code{main}
\item Useful for helper functions
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Singleton Object for the \code{main}}
\begin{chisel}
// A singleton object
object Example {
  
  // The start of a Scala program
  def main(args: Array[String]): Unit = {
    
    val e = new Example()
    e.print()
    e.set(42)
    e.print()
  }
}
\end{chisel}
\begin{itemize}
\item Compile and run it with sbt (or within Eclipse/IntelliJ):
\end{itemize}
\begin{chisel}
sbt "runMain Example"
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Scala Build Tool (sbt)}
\begin{itemize}
\item Downloads Scala compiler if needed
\item Downloads dependent libraries (e.g., Chisel)
\item Compiles Scala programs
\item Executes Scala programs
\item Does a lot of magic, maybe too much
\item Compile and run with:
\end{itemize}
\begin{chisel}
sbt "runMain simple.Example"
\end{chisel}
\begin{itemize}
\item Or even just:
\end{itemize}
\begin{chisel}
sbt run
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Build Configuration}
\begin{itemize}
\item Defines needed Scala version
\item Library dependencies
\item File name: \code{build.sbt}
\end{itemize}
\begin{chisel}
scalaVersion := "2.12.13"

scalacOptions ++= Seq(
  "-feature",
  "-language:reflectiveCalls",
)

resolvers ++= Seq(
  Resolver.sonatypeRepo("releases")
)
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Minimal Chisel Project Cont.}
\begin{chisel}
// Chisel 3.5
addCompilerPlugin("edu.berkeley.cs" % "chisel3-plugin" % "3.5.0" cross CrossVersion.full)
libraryDependencies += "edu.berkeley.cs" %% "chisel3" % "3.5.0"
libraryDependencies += "edu.berkeley.cs" %% "chiseltest" % "0.5.0"
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Show It}
\begin{itemize}
\item The absolute minimum is two files
\begin{itemize}
\item \code{build.sbt}
\item A single \code{.scala} file
\end{itemize}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{File Organization in Scala/Chisel}
\begin{itemize}
\item A Scala file can contain several classes (and objects)
\item For large classes use one file per class with the class name
\item Scala has packages, like Java
\item Use folders with the package names for file organization
\item \code{sbt} looks into current folder and \code{src/main/scala/}
\item Tests shall be in \code{src/test/scala/}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{File Organization in Scala/Chisel}
\dirtree{%
.1 project.
.2 src.
.3 main.
.4 scala.
.5 package.
.6 sub-package.
.3 test.
.4 scala.
.5 package.
.2 target.
.2 generated.
}
\end{frame}

\begin{frame}[fragile]{Chisel in Scala}
\begin{itemize}
\item Chisel components are Scala classes
\item Chisel code is in the constructor
\item Executed at object creation time
\item Builds the network of hardware objects
\item Testers are written in Scala to drive the tests
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Chisel Main}

\begin{itemize}
\item Create one top-level Module
\item Invoke the Verilog emitter from the Scala \code{main} (or App)
\item Following code generates Verilog code
\end{itemize}
\shortlist{../code/generate.txt}
\end{frame}


\begin{frame}[fragile]{Functions}
\begin{itemize}
\item Circuits can be encapsulated in functions
\item Each \emph{function call} generates hardware
\item Simple functions can be a single line
\end{itemize}
\begin{chisel}
  def adder(v1: UInt, v2: UInt) = v1 + v2
  
  val add1 = adder(a, b)
  val add2 = adder(c, d)
\end{chisel}
\end{frame}

\begin{frame}[fragile]{More Function Examples}
\begin{itemize}
\item Functions can also contain registers
\end{itemize}
\begin{chisel}
  def addSub(add: Bool, a: UInt, b: UInt) =
    Mux(add, a + b, a - b)

  val res = addSub(cond, a, b)

  def rising(d: Bool) = d && !RegNext(d)

  val edge = rising(cond)
\end{chisel}
\end{frame}

\begin{frame}[fragile]{The Counter as a Function}
\begin{itemize}
\item Longer functions in curly brackets
\item Last value is the return value
\end{itemize}
\begin{chisel}
def counter(n: UInt) = {
  
  val cntReg = RegInit(0.U(8.W))
  
  cntReg := cntReg + 1.U
  when(cntReg === n) {
    cntReg := 0.U
  }
  cntReg
}

val counter100 = counter(100.U)
\end{chisel}
\end{frame}


\begin{frame}[fragile]{Functions}
\begin{itemize}
\item Example from Patmos execute stage
\end{itemize}
\begin{chisel}
def alu(func: Bits, op1: UInt, op2: UInt): Bits = {
  val result = UInt(width = DATA_WIDTH)
  // some more lines...
  switch(func) {
    is(FUNC_ADD) { result := sum }
    is(FUNC_SUB) { result := op1 - op2 }
    is(FUNC_XOR) { result := (op1 ^ op2).toUInt }
    // some more lines
  }
  result
}
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Testing and Debugging}
\begin{itemize}
\item Nobody writes perfect code ;-)
\item We need a method to improve the code
\item In Java we can simply print the result:
\begin{itemize}
\item \code{println("42");}
\end{itemize}
\item What can we do in hardware?
\begin{itemize}
\item Describe the whole circuit and hope it works?
\item We can switch an LED on or off
\end{itemize}
\item We need some tools for \href{https://en.wikipedia.org/wiki/Debugging#/media/File:H96566k.jpg}{debugging}
\item Writing testers in Chisel
\end{itemize}
\end{frame}

\begin{frame}[fragile]{ScalaTest}
\begin{itemize}
\item Testing framework for Scala and Java
\item \code{sbt} understands ScalaTest
\item Add library to \code{build.sbt}
\begin{chisel}
libraryDependencies += "org.scalatest" %% "scalatest" % "3.1.4" % "test"
\end{chisel}
\item Run all tests with:
\begin{chisel}
sbt test
\end{chisel}
\item When all (unit) tests are ok, the test passes
\item A little bit funny syntax
\item ChiselTest is based on ScalaTest
\end{itemize}
\end{frame}

\begin{frame}[fragile]{ScalaTest Hello World}
\shortlist{../code/scalatest_hello_world.txt}
\end{frame}

\begin{frame}[fragile]{Testing with Chisel}
\begin{itemize}
\item A test contains:
\begin{itemize}
\item a device under test (DUT) and
\item the testing logic
\end{itemize}
\item Set input values with \code{poke}
\item Advance the simulation with \code{step}
\item Read the output values with \code{peek}
\item Compare the values with \code{expect}
\item Import following packages:
\shortlist{../code/test_import.txt}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{An Example DUT}
\begin{itemize}
\item A device-under test (DUT)
\item Just 2-bit AND logic
\shortlist{../code/test_dut.txt}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{A ChiselTest}
\begin{itemize}
\item Extends class \code{AnyFlatSpec} with \code{ChiselScalatestTester}
\item Has the device-under test (DUT) as parameter of the \code{test} function
\item Test function contains the test code
\item Testing code can use all features of Scala
\end{itemize}
\end{frame}

\begin{frame}[fragile]{A Simple Tester}
\begin{itemize}
\item Just using \code{println} for manual inspection
\shortlist{../code/test_bench_simple.txt}
\end{itemize}
\end{frame}


\begin{frame}[fragile]{A Real Tester}
\begin{itemize}
\item Poke values and \code{expect} some output
\shortlist{../code/test_bench.txt}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Generating Waveforms}
\begin{itemize}
\item Waveforms are timing diagrams
\item Good to see many parallel signals and registers
\begin{verbatim}
sbt "testOnly SimpleTest -- -DwriteVcd=1"
\end{verbatim}
\item Or as additional parameters to test:
\begin{chisel}
test(new DeviceUnderTest)
.withAnnotations(Seq(WriteVcdAnnotation))
\end{chisel}
\item IO signals and registers are dumped
\item Option \code{--debug} puts all wires into the dump
\item Generates a .vcd file
\item Viewing with GTKWave or ModelSim
\end{itemize}
\end{frame}


% Use this for 3 units/hours tutorial
%\input{generation.tex}

\begin{frame}[fragile]{Summary}
\begin{itemize}
\item Chisel is a library in Scala
\item RTL circuits are described in (plain) Chisel
\item Scala is the meta-circuit description language
\item Scala is used to write circuit generators
\item You write your tests in Scala
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Simulation Lab Session}
\begin{itemize}
\item Components and Small Sequential Circuits
\item \url{https://github.com/schoeberl/chisel-lab/tree/master/lab3}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{FPGA Lab Session}
\begin{itemize}
\item Examples from \url{https://github.com/schoeberl/chisel-examples}
\item Explore the ALU example
\begin{itemize}
\item It contains a tester
\item It can also be tested with the switches and LEDs on the FPGA
\end{itemize}
\item Explore the bubble FIFO example for wave form viewing
\item Do an example project from scratch
\begin{itemize}
\item But reuse Quartus files (from the ALU or knight example)
\item With a Chisel main
\item Some simple function with LEDs and switches
\begin{itemize}
\item E.g., moving light with direction change
\item Remember Knight Rider?
\end{itemize}
\item Running it in the FPGA
\end{itemize}
\end{itemize}
\end{frame}

\end{document}